<?php
namespace frontend\controllers;

use common\models\Wxuser;
use Yii;
use yii\base\Exception;
use yii\base\InvalidParamException;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use common\models\LoginForm;
use frontend\models\PasswordResetRequestForm;
use frontend\models\ResetPasswordForm;
use frontend\models\SignupForm;
use frontend\models\ContactForm;

/**
 * Site controller
 */
class SiteController extends Controller
{
    public $enableCsrfValidation = false;
    /**
     * Displays homepage.
     *
     * @return mixed
     */
    public function actionIndex()
    {
        $wechatApi = new \vendor\wxmessage\WechatCallbackApi();
        $wechatApi->valid();
    }

    public function actionReq()
    {
        $wechatApi = new \vendor\wxmessage\WechatCallbackApi();
        $wechatApi->responseMsg();
    }

    /**
     * Logs in a user.
     *
     * @return mixed
     */
    public function actionLogin()
    {
        if (!Yii::$app->user->isGuest) {
            return $this->goHome();
        }

        $model = new LoginForm();
        if ($model->load(Yii::$app->request->post()) && $model->login()) {
            return $this->goBack();
        } else {
            return $this->render('login', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Logs out the current user.
     *
     * @return mixed
     */
    public function actionLogout()
    {
        Yii::$app->user->logout();

        return $this->goHome();
    }

    /**
     * Displays contact page.
     *
     * @return mixed
     */
    public function actionContact()
    {
        $model = new ContactForm();
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            if ($model->sendEmail(Yii::$app->params['adminEmail'])) {
                Yii::$app->session->setFlash('success', 'Thank you for contacting us. We will respond to you as soon as possible.');
            } else {
                Yii::$app->session->setFlash('error', 'There was an error sending your message.');
            }

            return $this->refresh();
        } else {
            return $this->render('contact', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Displays about page.
     *
     * @return mixed
     */
    public function actionAbout()
    {
        return $this->render('about');
    }

    /**
     * 微信访问页面入口
     *
     * @return mixed
     */
    public function actionSignup()
    {
        $code = isset($_GET['code'])?$_GET['code']:'';
        if($code) {
            /** @var \callmez\wechat\sdk\Wechat $wechat $wechat */
            $wechat = Yii::$app->wechat;
            try{
                $wxInfo = $wechat->getOauth2AccessToken($code);
                $openid = $wxInfo['openid'];
                $user = Wxuser::find()->where(['openid'=>$openid])->one();

                if($openid==null){
                    $message = ['code'=>500,'message'=>'code过期'];
                    return json_encode($message);
                }
                if($user){
                    $message = ['code'=>200,'message'=>'登录成功','data'=>['openid'=>$user->openid,'userid'=>$user->id]];
                    return json_encode($message);
                }
                $menberInfo = $wechat->getMemberInfo($openid);
                $user = new Wxuser();
                $user->openid = $openid;
                $user->unionid = $wxInfo['unionid'];
                $user->wx_name = $menberInfo['nickname'];
                $user->wx_images = $menberInfo['headimgurl'];
                $user->wx_name = $menberInfo['nickname'];
                $user->username = $menberInfo['nickname'];
                $user->sex = $menberInfo['sex'];
                if($user->save()) {
                    $message = ['code'=>200,'message'=>'登录成功','data'=>['openid'=>$user->openid,'userid'=>$user->id]];
                    return json_encode($message);
                }
            } catch(Exception $e){
                $message = ['code'=>500,'message'=>$e->getMessage()];
                return json_encode($message);
            }
        }
        $message = ['code'=>500,'message'=>'访问路径非法！'];
        return json_encode($message);
    }

    /**
     * 更新token
     *
     * @return string
     */
    public function actionReftoken()
    {
        $post = Yii::$app->request->post();
        $token = new \frontend\token\tokenCheck();
        $user = $token->reftoken($post['userid'],$post['openid']);
        if($user){
            $message = ['code'=>200,'message'=>'token刷新成功','data'=>['openid'=>$user->openid,'userid'=>$user->user_id,'access_token'=>$user->access_token]];
            return json_encode($message);
        }
        $message = ['code'=>500,'message'=>'保存失败'];
        return json_encode($message);
    }

    /**
     * Requests password reset.
     *
     * @return mixed
     */
    public function actionRequestPasswordReset()
    {
        $model = new PasswordResetRequestForm();
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            if ($model->sendEmail()) {
                Yii::$app->session->setFlash('success', 'Check your email for further instructions.');

                return $this->goHome();
            } else {
                Yii::$app->session->setFlash('error', 'Sorry, we are unable to reset password for the provided email address.');
            }
        }

        return $this->render('requestPasswordResetToken', [
            'model' => $model,
        ]);
    }

    /**
     * Resets password.
     *
     * @param string $token
     * @return mixed
     * @throws BadRequestHttpException
     */
    public function actionResetPassword($token)
    {
        try {
            $model = new ResetPasswordForm($token);
        } catch (InvalidParamException $e) {
            throw new BadRequestHttpException($e->getMessage());
        }

        if ($model->load(Yii::$app->request->post()) && $model->validate() && $model->resetPassword()) {
            Yii::$app->session->setFlash('success', 'New password saved.');

            return $this->goHome();
        }

        return $this->render('resetPassword', [
            'model' => $model,
        ]);
    }
}
